let express = require('express')
let router = express.Router()
let jwt = require("../../utils/jwt")
let bcrypt = require("../../utils/bcrypt")
router.get('/', (req, res, next) => {
    // 处理登录业务
    let { username, password } = req.query
    if (!username || !password) {
        res.send({ err: 1, msg: '用户名或密码为必传参数' })
        return
    }
    req.mgdb.open({ collectionName: 'user' }).then(({ collection, client }) => {
        collection.find({ username }).toArray((err, result) => {
            if (err) {
                res.send({ err: 1, msg: '操作集合失败' })
            } else {
                if (result.length > 0) {
                    // 查询成功，库中有该用户数据，对比密码
                    let bl = bcrypt.compareSync(password, result[0].password)
                    if (bl) {
                        // 密码正确
                        let token = jwt.sign({ username, _id: result[0]._id })
                        delete result[0].password
                        delete result[0]._id
                        res.send({ err: 0, msg: '登陆成功', data: result[0], token })
                    } else {
                        res.send({ err: 1, msg: '密码有误' })
                    }
                } else {
                    // 查询失败，库中没有该用户名
                    res.send({ err: 1, msg: '用户名不存在' })
                }
            }
            client.close()
        })
    }).catch(
        e=>res.send(e)
    )
})
module.exports = router;